package com.lm.akka.service;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.pattern.Patterns;
import com.lm.akka.actor.PrintActor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;

@Service
public class ActorService {

    private final ActorSystem actorSystem;

    @Autowired
    public ActorService(ActorSystem actorSystem) {
        this.actorSystem = actorSystem;
    }

    public String sendMessage(String message) throws Exception {
        ActorRef actorRef = actorSystem.actorOf(Props.create(PrintActor.class));
        Future<Object> future = Patterns.ask(actorRef, message, 3000);
        Object result = scala.concurrent.Await.result(future, Duration.create(3, TimeUnit.SECONDS));
        return result.toString();
    }
}
